import legacy from '@vitejs/plugin-legacy';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import path from 'path';
import { ConfigEnv, UserConfigExport, loadEnv } from 'vite';
import eslintPlugin from 'vite-plugin-eslint';

import AutoImport from 'unplugin-auto-import/vite';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
// import ElementPlus from 'unplugin-element-plus/vite';
import qiankun from 'vite-plugin-qiankun';
const timeStamp = new Date().getTime();
function resolve(dir: string) {
  return path.join(__dirname, dir);
}

export default function ({ command, mode }: ConfigEnv): UserConfigExport {
  const env = loadEnv(mode, process.cwd());
  return {
    // base: '/wechat/',
    base: '/tcpi',
    server: {
      host: '0.0.0.0', // 解决不能通过ip访问
      hmr: true,
      port: 3000,
      cors: true,
      origin: "http://localhost:3000",
      proxy: {
        '/oa': {
          // target:'http://192.168.135.177:9004/',
          target: 'https://oa.mythinkcar.cn/',
          rewrite: (path) => path.replace(/^\/oa/, ''),
          changeOrigin: true
        },
        '/homepage': {
          target: env.VITE_HOME_PAGE,
          rewrite: (path) => path.replace(/^\/homepage/, ''),
          changeOrigin: true
        },
      }
    },
    plugins: [
      vue(),
      vueJsx(),
      // Components({
      //   resolvers: [VantResolver()],
      // }),
      eslintPlugin({
        fix: true
      }),
      legacy({
        targets: ['defaults', 'not IE 11']
      }),

      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), 'src/assets/svgs')],
        symbolId: 'icon-[dir]-[name]',
      }),
      AutoImport({
        imports: ['vue', 'vue-router', 'vuex'], // 自动导入vue和vue-router相关函数
        dts: 'src/auto-import.d.ts' // 生成 `auto-import.d.ts` 全局声明
      }),
      qiankun('tcpi', {
        useDevMode: true
      })
    ],
    resolve: {
      alias: {
        '@': resolve('./src')
      }
    },
    css: {},
    build: {
      minify: 'terser',
      terserOptions: {
        // 清除console和debugger
        compress: {
          drop_console: true,
          drop_debugger: true
        }
      },
      rollupOptions: {
        // 打包分类添加时间戳
        output: {
          chunkFileNames: `js/chunk/[name].${process.env.npm_package_version}.${timeStamp}.js`,
          entryFileNames: `js/entry/[name].${process.env.npm_package_version}.${timeStamp}.js`,
          assetFileNames: `[ext]/[name].${process.env.npm_package_version}.${timeStamp}.[ext]`,
          // 超大静态资源拆分
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id
                .toString()
                .split('node_modules/')[1]
                .split('/')[0]
                .toString();
            }
          }
        }
      }
    }
  };
}
